PHP simulation POST|GET operation implementation code

  • 2020-03-31 20:56:06
  • OfStack

Recently, I developed a social game and found that it is still quite common to use this thing. Here is a summary. On the one hand, I will keep some memories for myself, and on the other hand, I hope it will be helpful for everyone.

First, let's look at the requirements. If we develop a social game on facebook, we need to call its interface to get the information of the user's friends on facebook. At this time, we need to access an address provided by facebook. Of course, when you visit him, he needs to verify your access to prevent illegal requests. At this point you have to post| to it to get some parameters.
The following address:
 
$url_with_get= "http://api.facebook.com/restserver.php?method=facebook.friends.get&session_key=&api_key=1232121311&v=1.0"; 
$post = array('sig'=>12312123234353); 

How to get data from this address, briefly introduce the following code:
 
if(function_exists('curl_init')) 
{ 
  $ch = curl_init(); 
  curl_setopt($ch, CURLOPT_URL, $url_with_get); 
  curl_setopt($ch, CURLOPT_POST, 1); 
  curl_setopt($ch, CURLOPT_POSTFIELDS, $post); 
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
  $result = curl_exec($ch); 
  curl_close($ch); 
} 
else 
{ 
  $content = http_build_query($post) 
  $content_length = strlen($content); 
  $context = 
  array('http' => 
array('method' => 'POST', 
'user_agent' => $user_agent, 
'header' => 'Content-Type: ' . $content_type . "rn" . 
'Content-Length: ' . $content_length, 
'content' => $content)); 
$context_id = stream_context_create($context); 
$sock = fopen($url_with_get, 'r', false, $context_id); 
$result = ''; 
if ($sock) 
  { 
    while (!feof($sock)) 
  $result .= fgets($sock, 4096); 
  fclose($sock); 
} 
return $result; 
} 
} 

The code above calls facebook's interface in two ways, the first to determine whether the user's environment turns on the curl library, and the second to turn on the library, and then to get the request. You can refer to the manual for detailed parameter explanation.
A hint here is that since we normally need to get the return result of the call interface, we set the value CURLOPT_RETURNTRANSFER to return the result to the variable.
The second is intuitive, turning the url request into a file stream for processing.

Related articles: